package com.universityJob.modules.sys.service.impl;

import com.universityJob.common.utils.R;
import com.universityJob.modules.sys.service.SysDataSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author mao on 2021/5/24.
 * @version 1.0 maozhijob@163.com
 */
@Service("sysDataSourceService")
public class SysDataSourceServiceImpl implements SysDataSourceService {

    @Value("${spring.datasource.druid.username}")
    private String dataSourceUser;
    @Value("${spring.datasource.druid.password}")
    private String dataSourcePassword;
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public int BackupDataSource(String path) throws IOException {
        InputStream inputStream = null;//得到输入流，写成.sql文件
        InputStreamReader reader = null;
        BufferedReader br = null;
        FileOutputStream fileOutputStream = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            //-u后面是用户名，-p是密码-p后面最好不要有空格，-family是数据库的名字
            String command = "mysqldump -u "+dataSourceUser+" -p"+dataSourcePassword+" university-job --ignore-table=university-job.qrtz_triggers --ignore-table=university-job.qrtz_job_details  --ignore-table=university-job.qrtz_blob_triggers";
            logger.info("执行命令 {}",command);
            Process process = runtime.exec(command);
            inputStream = process.getInputStream();
            reader = new InputStreamReader(inputStream);
            br = new BufferedReader(reader);
            String s = null;
            StringBuffer sb = new StringBuffer();
            while((s = br.readLine()) != null){
                sb.append(s+"\r\n");
            }
            s = sb.toString();
            File file = new File(path);
            file.getParentFile().mkdirs();
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(s.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }finally {
            fileOutputStream.close();
            br.close();
            reader.close();
            inputStream.close();
        }
        return 1;
    }

    @Override
    public int RecoverDataSource(File file) throws IOException {
        OutputStream outputStream = null;
        BufferedReader br = null;
        OutputStreamWriter writer = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            //-u后面是用户名，-p是密码-p后面最好不要有空格，-family是数据库的名字，--default-character-set=utf8，这句话一定的加
            //我就是因为这句话没加导致程序运行成功，但是数据库里面的内容还是以前的内容，最好写上完成的sql放到cmd中一运行才知道报错了
            //错误信息：
            //mysql: Character set 'utf-8' is not a compiled character set and is not specified in the '
            //C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\Index.xml' file ERROR 2019 (HY000): Can't
            // initialize character set utf-8 (path: C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\)，
            //又是讨人厌的编码问题，在恢复的时候设置一下默认的编码就可以了。
            String command = "mysql -u "+dataSourceUser+" -p"+dataSourcePassword+" --default-character-set=utf8 university-job";
            logger.info("执行命令 {}",command);
            Process process = runtime.exec(command);

            outputStream = process.getOutputStream();
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String str = null;
            StringBuffer sb = new StringBuffer();
            while((str = br.readLine()) != null){
                sb.append(str+"\r\n");
            }
            str = sb.toString();
            writer = new OutputStreamWriter(outputStream,"utf-8");
            writer.write(str);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        } finally {
            outputStream.close();
            br.close();
            writer.close();
        }
        return -2;
    }
}
